package main

import (
	"errors"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

const (
	DefaultRemoteAddress   = "http://202.204.48.66/"
	HttpContentType = "application/x-www-form-urlencoded; param=value"
	HttpUserAgent   = "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Mobile Safari/537.36"
)

// User stores user information
type User struct {
	Username string
	Password string
	Ipv6Addr string
}

func (u *User) Post(remoteAddress string) (error, string) {
	v := url.Values{"DDDDD": {u.Username}, "upass": {u.Password}, "v6ip": {u.Ipv6Addr}, "0MKKey": {"123456789"}}
	body := strings.NewReader(v.Encode())

	client := &http.Client{}
	request, _ := http.NewRequest("POST", remoteAddress, body)
	request.Header.Set("Content-Type", HttpContentType)
	request.Header.Set("User-Agent", HttpUserAgent)
	request.Header.Set("Cookie", "myusername="+u.Username+";username="+u.Username)
	request.Header.Set("Referer", remoteAddress)

	if resp, err := client.Do(request); err != nil {
		return err, "Whoops! Error sending http request."
	} else {
		defer resp.Body.Close()
		if body, err := ioutil.ReadAll(resp.Body); err != nil {
			return err, "Whoops! Error while reading http response body."
		} else {
			if strings.Contains(string(body), "successfully") || strings.Contains(string(body), "v46ip") {
				return nil, ""
			} else {
				return errors.New("login failed"), "Oh, login failed. Maybe you have a wrong password?"
			}
		}
	}
}
